/*
 * @Author: AiLjx
 * @Date: 2022-06-03 15:28:06
 * @LastEditors: AiLjx
 * @LastEditTime: 2022-06-25 19:00:42
 */
import React, { Component, useRef } from "react";

class Input extends Component {
    state = {
        value: "",
    };
    putValue = (e) => {
        this.setState({
            value: e.target.value,
        });
    };
    clear = () => {
        this.setState({
            value: "",
        });
    };
    render() {
        return (
            <input
                type='text'
                value={this.state.value}
                onChange={(e) => this.putValue(e)}
            />
        );
    }
}

const App = () => {
    const usename = useRef();
    return (
        <div>
            {/* ref获取组件实例，可以调用组件的方法获取组件的状态等 */}
            <Input ref={usename}></Input>
            <button
                onClick={() => {
                    // 通过ref获取子组件的状态
                    console.log(usename.current.state.value);
                    alert("你输入的是", usename.current.state.value);
                }}>
                登陆
            </button>
            <button
                onClick={() => {
                    usename.current.setState({
                        value: "",
                    });
                }}>
                取消输入（方式1）
            </button>
            <button
                onClick={() => {
                    usename.current.clear();
                }}>
                取消输入（方式2）
            </button>
        </div>
    );
};

export default App;
